// User/pages/Elderly/index.js
import { logger } from '@/utils/util'
import { customNavigate } from '@/utils/route'
/**
 * 使用人列表页
 * 
 * create & edit by cyj at 2024-09-10
 * */
const app = getApp()
import {
    fetchElderlyList
} from '../../../services/elderly';
let page_num = 1;
Page({
    data: {
        currentIndex: 0,
        list: [],
        staticPrefix: app.globalData.STATIC_PREFIX
    },
    onLoad(options) {},
    onShow() {
        this.searchElderlyList()
    },
    async searchElderlyList() {
        const res = await fetchElderlyList();
        if (res.return_code == 'SUCCESS') {
            this.setData({
                list: res.data
            }, () => {
                if (wx.getStorageSync('elderlyInfo')) {
                    let currentIndex = res.data.findIndex((item) => item.id === wx.getStorageSync('elderlyInfo').id)
                    this.setData({
                        currentIndex
                    })
                }
            })
        }
    },
    onCheck(e) {  
        let { item, index } = e.currentTarget.dataset;  
        this.setData({ currentIndex: index }, () => {  
            wx.setStorage({  
                key: 'elderlyInfo',  
                data: item,  
                success: () => {  
                    wx.switchTab({  
                        url: '/pages/Home/index',  
                        success: () => {  
                            logger.log('Successfully switched to Home tab');  
                        },  
                        fail: (error) => {  
                            logger.error('Failed to switch tab:', error);  
                            // 如果 switchTab 失败，尝试使用 navigateTo  
                            customNavigate({  
                                url: '/pages/Home/index',  
                                fail: (navError) => {  
                                    logger.error('Both switchTab and navigateTo failed:', navError);  
                                }  
                            });  
                        }  
                    });  
                },  
                fail: (error) => {  
                    logger.error('Failed to set storage:', error);  
                }  
            });  
        });  
    }  
})